const express = require('express');
const db = require('../database');
const router = express.Router();

// 获取所有学生信息
router.get('/', (req, res) => {
  db.query('SELECT * FROM students', (err, results) => {
    if (err) {
      return res.status(500).send('数据库查询失败');
    }
    res.json(results);  
  });
});

// 查询学生信息
router.get('/search', (req, res) => {
  const { name } = req.query;  // 从查询参数中获取姓名
  if (!name) {
    return res.status(400).send('请提供查询条件');
  }
  const query = 'SELECT * FROM students WHERE name LIKE ?';
  db.query(query, [`%${name}%`], (err, results) => {
    if (err) {
      return res.status(500).send('数据库查询失败');
    }
    res.json(results);
  });
});

// 添加学生信息
router.post('/add', (req, res) => {
  const { name, age, major } = req.body;
  const query = 'INSERT INTO students (name, age, major) VALUES (?, ?, ?)';
  db.query(query, [name, age, major], (err, results) => {
    if (err) {
      return res.status(500).send('添加学生失败');
    }
    res.redirect('/students.html');
  });
});

// 编辑学生信息
router.get('/edit/:id', (req, res) => {
  const { id } = req.params;
  db.query('SELECT * FROM students WHERE id = ?', [id], (err, results) => {
    if (err || results.length === 0) {
      return res.status(404).send('学生信息未找到');
    }
    res.redirect('/students.html');
  });
});

// 更新学生信息
router.post('/edit/:id', (req, res) => {
  const { id } = req.params;
  const { name, age, major } = req.body;
  const query = 'UPDATE students SET name = ?, age = ?, major = ? WHERE id = ?';
  db.query(query, [name, age, major, id], (err, results) => {
    if (err) {
      return res.status(500).send('更新学生信息失败');
    }
    res.redirect('/students.html');
  });
});

// 删除学生信息
router.get('/delete/:id', (req, res) => {
  const { id } = req.params;
  db.query('DELETE FROM students WHERE id = ?', [id], (err, results) => {
    if (err) {
      return res.status(500).send('删除学生失败');
    }
    res.redirect('/students.html');
  });
});

module.exports = router;
